/**
 * @file hb_app.c
 * @synopsis  
 * @author wen wjcapple@163.com
 * @version 2.0
 * @date 2016-07-05
 */


#include "gpio_ctrl.h"
#include "program_run_log.h"

#ifdef __cplusplus
extern "C" {
#endif

int32_t GPIO_NUM_SLOT = 4;
int32_t GPIO_NUM_FRAME = 4;
int32_t GPIO_NUM_CH_ALARM = 2;	
int32_t open_gpio()
{
	int32_t ret,i,fd;
	char env_name[64] = {0};
	
	/*
	 * 2017-09-01 
	 * 根据通道确定告警灯的数目
	 * 2ch 4ch 每个通道独立的告警灯
	 * 8ch 每两个通道共享一个告警灯
	*/
	if( CH_NUM > 0 && CH_NUM <= 4)
		GPIO_NUM_CH_ALARM = CH_NUM;
	else 
		 GPIO_NUM_CH_ALARM = 4;

	gpio_fd.is_ok = 0;
	//机框号
	for(i = 0; i < GPIO_NUM_FRAME;i++)
	{
		snprintf(env_name,64, "DEVICE_PIN_FRAME_B%d",i);
		fd = get_gpio_fd(env_name, O_RDONLY);
		gpio_fd.frame[i] = fd;
	}
	//槽位号
	for(i = 0; i < GPIO_NUM_SLOT;i++)
	{
		snprintf(env_name,64, "DEVICE_PIN_SA%d",i);
		fd = get_gpio_fd(env_name, O_RDONLY);
		gpio_fd.slot[i] = fd;
	}
	//告警通道
	for(i = 0; i < GPIO_NUM_CH_ALARM;i++)
	{
		snprintf(env_name,64 ,"DEVICE_PIN_%d_ALARM", i + 1);
		fd = get_gpio_fd(env_name, O_WRONLY);
		gpio_fd.alarm_ch[i] = fd;
	}

	snprintf(env_name,64 ,"DEVICE_PIN_LED_RUN");
	fd = get_gpio_fd(env_name, O_RDWR);
	gpio_fd.run = fd;

/*
	snprintf(env_name,64 ,"DEVICE_PIN_UF_CU_ALARM");
	fd = get_gpio_fd(env_name, O_WRONLY);
	gpio_fd.alarm_commu = fd;
*/	
	
	snprintf(env_name,64 ,"DEVICE_PIN_TO_CU_ALARM");
	fd = get_gpio_fd(env_name, O_WRONLY);
	gpio_fd.alarm_total = fd;

	snprintf(env_name,64 ,"DEVICE_PIN_TOTAL_ALARM");
	fd = get_gpio_fd(env_name, O_WRONLY);
	gpio_fd.alarm_total_1 = fd;

	snprintf(env_name,64 ,"DEVICE_PIN_SUBNET");
	fd = get_gpio_fd(env_name,O_RDONLY);
	gpio_fd.ip_flag = fd;
	gpio_fd.is_ok = 1;

	
	return 0;
}
int32_t read_gpio_val(int32_t fd, char buf[], int32_t bytes)
{
	int32_t ret,i;
	char cval,*pval;
	pval = &cval;
	for(i = 0; i < bytes;i++)
	{
		lseek(fd, 0, SEEK_SET);
		ret = read(fd, pval, 1);
		buf[i] = atoi(pval);
		assert(ret == 1);
	}
	return bytes;
}
int32_t write_gpio_val(int32_t fd, int32_t val)
{
	int32_t ret;
	char cval;
	if(val == 1)
		cval = 49;
	else
		cval = 48;

	lseek(fd, 0, SEEK_SET);
	ret = write(fd, &cval, 1);
	//PR_X("fd %d ret %d bytes %d errno  %d val %d " ,fd,ret,bytes,errno,buf[0]);
	assert(ret == 1);
	return ret;
}
int32_t get_gpio_fd(const char *env_name,int32_t mod)
{
	int32_t fd;
	char path[128] = "/sys/class/gpio/\0";
	char cval[] = "/value\0"; 
	char *env = NULL;
	env = getenv(env_name);
	assert (env != NULL);
	strncat(path,env,64);
	strncat(path,cval,8);
	fd = open(path,mod);
	PR_X("\n%s \n%s \n%s \nfd=%d", env_name, env,path,fd);
	assert(fd != -1);
	return fd;
}

//按照C风格编译
#ifdef __cplusplus
}
#endif
